package com.example.client_group5;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import util.HttpClientFactory;

import android.os.Bundle;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class RetweetActivity extends AppBaseActivity {

	private TextView title;
	int itemsPerPage = 6;
	boolean loadingMore = false;
	private ArrayList<User> users;
	private UserItemAdapter adapter;
	private int max_id = -1;
	private ListView listView;
	private View footerView;
	String[] infor;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //Set view cho Retweet Activity
		setContentView(R.layout.activity_follow);
        registerBaseActivityReceiver();
        title = (TextView)findViewById(R.id.title);
        
        title.setText("Retweeted By");
        
        title.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				closeAllActivities();
			}
		});
        Bundle b=getIntent().getExtras();
        
        infor=b.getStringArray("tweet"); 
        
        this.listView = (ListView)findViewById(R.id.ListViewId);
        users=new ArrayList<User>();
        adapter=new UserItemAdapter(this, R.layout.listfollowing, users);
        
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
        listView.addFooterView(footerView);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new OnScrollListener() {
			
        	//useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				
				//what is the bottom item that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;				
				Log.d("tag", "lastInScreen: " + lastInScreen + "/ totalItemCount: " + totalItemCount);
				//is the bottom item visible & not loading more already ? Load more !
				if((lastInScreen == totalItemCount) && !(loadingMore)){
					loadingMore = true;
					Log.d("tag", "Loading more item...........");
					Thread thread =  new Thread(null, loadMoreListItems);
			        thread.start();
				}
				
			}
		});
    }
     
    public ArrayList<User> getRetweeter(int tweet_id,int count){

    	String getUrl = Setting.ipServer + "api/tweet/get-retweeted-users/tweet_id/"+tweet_id
    			+"/count/"+count;
    	if(max_id!=-1)
    		getUrl+="/max_id/"+max_id;
    	Log.d("tag", "request:"+getUrl);
    	ArrayList<User> users=new ArrayList<User>();
    	
    	//create connection to server
    	HttpClient client=HttpClientFactory.getThreadSafeClient();
    	HttpGet get=new HttpGet(getUrl);
    	ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();
		String responseBody = null;
		try {
		    responseBody = client.execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("Request", ">>>>>>>"+getUrl);
		Log.d("tag", "Tra ve: " + responseBody);
		
		//JSONObject jsonObject = null;
		JSONArray userArray=null;
		try{
			
			userArray=new JSONArray(responseBody);
			
			for(int i=0;i<userArray.length();i++)
			{
				JSONObject userItem=userArray.getJSONObject(i);
				
				int id=userItem.getInt("id");
				
				if(id < this.max_id || this.max_id == -1) {
					this.max_id = id;
				}
				
				
				boolean is_following=userItem.getBoolean("is_following");
				String user_name=userItem.get("username").toString();
				String user_fullname=userItem.get("fullname").toString();
				String avatar=userItem.get("avatar").toString();	
				users.add(new User(id,user_name, user_fullname, avatar, 0, 0, 0,false,
						is_following,false,"",""));
				
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return users;
    }
    
    //Runnable to load the items 
    private Runnable loadMoreListItems = new Runnable() {	
 
		@Override
		public void run() {
			//Set flag so we cant load new items 2 at the same time
			Log.d("tag", "dkm");
	    	try{
	    		Thread.sleep(1000);
	    	}catch(InterruptedException e){}
	    	users = new ArrayList<User>();
	    	int tweet_id=Integer.parseInt(infor[0]);
	    	users = getRetweeter(tweet_id,itemsPerPage);
	    	runOnUiThread(returnRes);
	        
		}
	};	
	
	//Since we cant update our UI from a thread this Runnable takes care of that! 
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
        	if(users != null && users.size() > 0){
        		for(int i = 0; i < users.size(); i ++){
        			adapter.add(users.get(i));
        		}
        	}
            adapter.notifyDataSetChanged();
			//Done loading more.
            if(users.size() > 0)
            	loadingMore = false;
            else{
            	listView.removeFooterView(footerView);
            }
        }
    };
    
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			finish();
		}
		return false;
	}
    public void onDestroy(){
    	super.onDestroy();
    	System.gc();
    	unRegisterBaseActivityReceiver();
    }
}
